package com.example.mysqlview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private Button bt_add;
    private RecyclerView rcvStu;

    private List<Fruit> list = new ArrayList<>();

    private FruitAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt_add = findViewById(R.id.bt_add);
        rcvStu = findViewById(R.id.rv_rv);

        bt_add.setOnClickListener(view -> {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, AddActivity.class);
            startActivity(intent);
        });

        adapter = new FruitAdapter(MainActivity.this, list);
        rcvStu.setAdapter(adapter);

        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
        rcvStu.setLayoutManager(manager);
    }

    @Override
    protected void onResume() {
        super.onResume();
        readFromSQLite();
        adapter.notifyDataSetChanged();
    }

    private void readFromSQLite() {
        list.clear();
        MySQLiteOpenHelper helper = new MySQLiteOpenHelper(MainActivity.this, "fru.db", null, 1);
        SQLiteDatabase readableDatabase = helper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("fruit", null, null, null, null, null, null);
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            String id = cursor.getString(0);
            String name = cursor.getString(1);
            int price = cursor.getInt(2);
            Fruit fruit = new Fruit(id, name, price);
            list.add(fruit);
        }
        cursor.close();
        readableDatabase.close();
    }
}